<?php
if(!defined('IN_WOGU')) {
    exit('Access Denied');
}

Loader::loadClass('Model');

class SpiderLogs extends Model
{
    protected $table_name = 'spider_logs';
    protected $_spiders = array('AcoonBot', 'Baiduspider', 'Ezooms', 'Googlebot', 'JikeSpider', 'YRSpider', 'YoudaoBot', 'bingbot', 'Googlebot-Mobile', 'Sogou web spider', 'Sosospider', 'msnbot-media');

    public function start() {
        if(strpos($_SERVER['HTTP_USER_AGENT'], 'spider') !== false || strpos($_SERVER['HTTP_USER_AGENT'], 'bot') !== false || strpos($_SERVER['HTTP_USER_AGENT'], 'slurp') !== false) {
            $spiderid = null;
            foreach ($this->_spiders as $k => $v) {
                 if(strpos($_SERVER['HTTP_USER_AGENT'], $v) !== false) {
                     $spiderid = $k;
                     break;
                 }
            }
            
            //记录新蜘蛛
            if($spiderid === null) {
                $cachefile = LIB_ROOT . 'data/cache/unknowspider.txt';
                $fp = fopen($cachefile, 'a+');
                fwrite($fp, $_SERVER['HTTP_USER_AGENT']."\n\n");
                fclose($fp);
                return;
            }
            
            //更新蜘蛛爬行记录
            $day = strtotime(date('Y-m-d', SYS_TIME));
            $log = $this->get_one(array('day' => $day, 'spider_id' => $spiderid));
            if($log) {
                $data = array('viewnum' => $log['viewnum'] + 1, 'lastvist' => SYS_TIME);
                $this->update($data, array('id' => $log['id']));
                return;
            }
            
            $data = array('viewnum' => 1, 'lastvist' => SYS_TIME, 'day' => $day, 'spider_id' => $spiderid);
            $this->insert($data);
        }
    }
}